package test06;

import java.util.ArrayList;
import java.util.List;

public class KernelFusionStrategy implements InferenceOptimizationStrategy {
    private List<String> fusionPatterns = new ArrayList<>();

    public KernelFusionStrategy() {
        fusionPatterns.add("MatMul+Add");
        fusionPatterns.add("LayerNorm+GeLU");
    }

    @Override
    public Tensor[] optimizeInference(Model model, RequestData[] requests) {
        System.out.println("🔗 应用内核融合策略");
        System.out.println("   - 融合模式: " + fusionPatterns);

        // 模拟内核融合
        for (String pattern : fusionPatterns) {
            System.out.println("   - 融合操作: " + pattern);
        }
        System.out.println("   - 减少内核启动开销和内存访问次数");

        Tensor[] preprocessedInputs = preprocessInputs(requests);
        return model.forward(preprocessedInputs);
    }

    private Tensor[] preprocessInputs(RequestData[] requests) {
        Tensor[] inputs = new Tensor[requests.length];
        for (int i = 0; i < requests.length; i++) {
            inputs[i] = new Tensor(new float[]{1.0f, 0.0f, 0.5f}, new int[]{1, 3});
        }
        return inputs;
    }

    public void addFusionPattern(String pattern) {
        fusionPatterns.add(pattern);
    }
}